package com.smart.community.region.service;

import com.smart.community.region.vo.CommunityVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 社区缓存服务
 * 用于缓存社区信息，提高查询性能
 * 
 * @author Wu.Liang
 * @since 2025-01-30
 */
@Slf4j
@Service
public class CommunityCacheService {

    @Autowired
    private ICommunityService communityService;

    // 本地缓存，用于存储社区信息
    private final Map<Long, CommunityVO> communityCache = new ConcurrentHashMap<>();

    /**
     * 根据社区ID获取社区信息（带缓存）
     * 
     * @param communityId 社区ID
     * @return 社区信息
     */
    @Cacheable(value = "community", key = "#communityId")
    public CommunityVO getCommunityById(Long communityId) {
        if (communityId == null) {
            return null;
        }

        try {
            // 先从本地缓存获取
            CommunityVO cachedCommunity = communityCache.get(communityId);
            if (cachedCommunity != null) {
                log.debug("从本地缓存获取社区信息，社区ID：{}", communityId);
                return cachedCommunity;
            }

            // 从数据库获取
            CommunityVO community = communityService.getCommunityById(communityId);
            if (community != null) {
                // 放入本地缓存
                communityCache.put(communityId, community);
                log.debug("社区信息已缓存，社区ID：{}，社区名称：{}", communityId, community.getCommunityName());
            }

            return community;
        } catch (Exception e) {
            log.error("获取社区信息失败，社区ID：{}", communityId, e);
            return null;
        }
    }

    /**
     * 批量获取社区信息（带缓存）
     * 
     * @param communityIds 社区ID列表
     * @return 社区信息Map
     */
    public Map<Long, CommunityVO> getCommunitiesByIds(List<Long> communityIds) throws Exception {
        Map<Long, CommunityVO> result = new ConcurrentHashMap<>();
        
        if (communityIds == null || communityIds.isEmpty()) {
            return result;
        }

        for (Long communityId : communityIds) {
            CommunityVO community = getCommunityById(communityId);
            if (community != null) {
                result.put(communityId, community);
            }
        }
        return result;
    }

    /**
     * 清除指定社区的缓存
     * 
     * @param communityId 社区ID
     */
    @CacheEvict(value = "community", key = "#communityId")
    public void evictCommunityCache(Long communityId) throws Exception {
        if (communityId != null) {
            communityCache.remove(communityId);
            log.debug("清除社区缓存，社区ID：{}", communityId);
        }
    }

    /**
     * 清除所有社区缓存
     */
    @CacheEvict(value = "community", allEntries = true)
    public void evictAllCommunityCache() throws Exception {
        communityCache.clear();
        log.info("清除所有社区缓存");
    }

    /**
     * 预热社区缓存
     * 
     * @param communityIds 需要预热的社区ID列表
     */
    public void warmUpCache(List<Long> communityIds) throws Exception {
        if (communityIds == null || communityIds.isEmpty()) {
            return;
        }

        log.info("开始预热社区缓存，社区数量：{}", communityIds.size());
        
        for (Long communityId : communityIds) {
            try {
                getCommunityById(communityId);
            } catch (Exception e) {
                log.warn("预热社区缓存失败，社区ID：{}", communityId, e);
                throw e;
            }
        }
        
        log.info("社区缓存预热完成");
    }

    /**
     * 获取缓存统计信息
     * 
     * @return 缓存统计信息
     */
    public Map<String, Object> getCacheStats() throws Exception {
        Map<String, Object> stats = new ConcurrentHashMap<>();
        stats.put("cacheSize", communityCache.size());
        stats.put("cachedCommunityIds", communityCache.keySet());
        return stats;
    }
} 